package com.wxl.micro.service.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;

/***
 *    前后端分离项目的跨域配置。
 *    也可以使用yml的配置文件格式：
 *
 *      spring:
 *        application:
 *          name: api-gateway
 *        cloud:
 *          gateway:
 *            globalcors:
 *              cors-configurations:
 *                '[/**]':   # 允许跨域访问的资源
 *                  allowedOrigins: "*"   #跨域允许来源
 *                  allowedMethods:
 *                    - GET
 *                    - POST
 *
 */
@Configuration
public class CorsConfig {
    @Bean
    public CorsWebFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedMethod("*");   // 允许的method
        config.addAllowedOrigin("*");   // 允许的来源
        config.addAllowedHeader("*");   // 允许的请求头参数

        // 运行访问的资源
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/**", config);

        return new CorsWebFilter(source);
    }
}